import store from '@/store';
import cache from '@/utils/cache.js';
import Jconfig from '@/config/config.js'
import { rejects } from 'assert';
import { login } from '@/api/api.js';
const PassportBiz = require('@/utils/comm/biz/passport_biz.js');
const WorkBiz = require('@/utils/biz/work_biz.js');
const AdminBiz = require('@/utils/comm/biz/admin_biz.js');
export default {
	/**
	 * opt  object | string
	 * to_url object | string
	 * 例:
	 * this.Tips('/pages/test/test'); 跳转不提示
	 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
	 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
	 * tab=1 一定时间后跳转至 table上
	 * tab=2 一定时间后跳转至非 table上
	 * tab=3 一定时间后返回上页面
	 * tab=4 关闭所有页面，打开到应用内的某个页面
	 * tab=5 关闭当前页面，跳转到应用内的某个页面
	 */
	Tips: function(opt, to_url) {
		if (typeof opt == 'string') {
			to_url = opt;
			opt = {};
		}

		let title = opt.title || '';
		let icon = opt.icon || 'none';
		let endtime = opt.endtime || 2000;
		let success = opt.success || null;

		if (title) {
			uni.showToast({
				title: title,
				icon: icon,
				duration: endtime,
				success
			})
		}
		if (to_url != undefined) {
			if (typeof to_url == 'object') {
				let tab = to_url.tab || 1,
					url = to_url.url || '';
				switch (tab) {
					case 1:
						//一定时间后跳转至 table
						setTimeout(function() {
							uni.switchTab({
								url: url
							})
						}, endtime);
						break;
					case 2:
						//跳转至非table页面
						setTimeout(function() {
							uni.navigateTo({
								url: url,
							})
						}, endtime);
						break;
					case 3:
						//返回上页面
						setTimeout(function() {
							// #ifndef H5
							uni.navigateBack({
								delta: parseInt(url),
							})
							// #endif
							// #ifdef H5
							history.back();
							// #endif
						}, endtime);
						break;
					case 4:
						//关闭所有页面，打开到应用内的某个页面
						setTimeout(function() {
							uni.reLaunch({
								url: url,
							})
						}, endtime);
						break;
					case 5:
						//关闭当前页面，跳转到应用内的某个页面
						setTimeout(function() {
							uni.redirectTo({
								url: url,
							})
						}, endtime);
						break;
				}

			} else if (typeof to_url == 'function') {
				setTimeout(function() {
					to_url && to_url();
				}, endtime);
			} else {
				//没有提示时跳转不延迟
				setTimeout(function() {
					uni.navigateTo({
						url: to_url,
					})
				}, title ? endtime : 0);
			}
		}
	},
	
	/**
	 * 已有文件地址，直接上传
	 * @param filePath 上传文件路径 
	 * @param successFn success回调 
	 * @param errorFn err回调
	 */
	uploadFile(filePath, successFn, errorFn) {
		let that = this;
		return new Promise(resolve => {
			uni.showLoading({title:"文件上传中"});
			
			// 构建请求头，参考 request.js 的逻辑
			let headers = {
				// #ifdef MP
				"Content-Type": "multipart/form-data",
				// #endif
			};
			
			// 获取应用配置中的 tenant_id
			const cachedConfig = cache.get('app_config');
			if(cachedConfig){
				try {
					let appConfig = JSON.parse(cachedConfig);
					let configJson = JSON.parse(appConfig.configValue);
					headers.tenant_id = configJson.tenantId;
				} catch(e) {
					console.log('解析缓存配置失败:', e);
				}
			}
			
			// 设置各种 token
			headers.user_token = PassportBiz.getToken() == null ? '' : PassportBiz.getToken().token;
			headers.work_token = WorkBiz.getWorkUserToken() || '';
			headers.token = cache.get('token') || '';
			headers.admin_token = AdminBiz.getAdminUserToken() || '';
			
			// 设置 Authorization，优先级: admin_token > work_token > user_token
			headers.Authorization = `Bearer ${AdminBiz.getAdminUserToken() || WorkBiz.getWorkUserToken() || (PassportBiz.getToken() == null ? '' : PassportBiz.getToken().token) || ''}`;
			
			// 添加设备 token
			const deviceToken = store.state.app.deviceToken;
			if (deviceToken) {
				headers['pdf-device-token'] = deviceToken;
			}
			
			// 添加用户 token（兼容性）
			headers.usertoken = PassportBiz.getToken() == null ? '' : PassportBiz.getToken().token;
			
			uni.uploadFile({
				url: `${Jconfig.baseURL}/file/upload`,
				filePath: filePath,
				name: 'file',
				header: headers,
				success: (res) => {
					uni.hideLoading();
					if (res.statusCode == 403) {
						that.Tips({ title: res.data })
					} else {
						let data = res.data ? JSON.parse(res.data) : {}
						if (data.code == 200) {
							successFn && successFn(data)
						} else {
							that.Tips({ title: data.message })
							errorFn && errorFn(data)
						}
					}
				},
				fail: (err) => {
					console.log('🐛🐛🐛',err)
					uni.hideLoading()
					that.Tips({title: '文件上传错误'})
					errorFn && errorFn(err)
				},
				complete: () => {
					resolve()
				}
			})
		});
	},
	toLogin: function () {
		let _this = this
		return new Promise((resolve,reject) => {
			uni.login({
				provider: 'weixin',
				success: function (res) {
					login({ code: res.code })
						.then((r) => {
							store.commit('LOGIN', r.token)
							cache.set('userInfo', r.userInfo);
							resolve(true)
						})
						.catch((err) => {
							resolve(false)
							console.log('🐛🐛🐛',err);
						});
				}
			});
		})
	}
}